<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	public function __construct() {
		parent::__construct();
		$this->load->model('Login_model', 'loginModel');
	}
	//页面渲染
	public function index()
	{
		$this->load->view('admin/Login/login');
	}
	public function login()
	{
		$username=$this->input->post('username');
		$password=$this->input->post('password');
		if(!($username&&$password))
		{
			die(json_encode(['code'=>0,'content'=>'缺少参数!']));
		}
		$adminInfo=$this->loginModel->getAdminUsername($username);
		if(!$adminInfo)
		{
			die(json_encode(['code'=>0,'content'=>'用户名错误，请重新输入!']));
		}
		if($adminInfo->auto!=1)
		{
			die(json_encode(['code'=>0,'content'=>'账号已被禁用，请联系管理员!']));
		}
		$passwordHash = $this->hashPassword($password);
		if($adminInfo->password !== $passwordHash)
		{
			$adminInfo->login_fail += 1;
			$this->loginModel->operationAdmin($adminInfo->id,$adminInfo->login_fail,'login_fail');
			die(json_encode(['code'=>0,'content'=>'密码错误!']));
		}
		if($adminInfo->login_fail >= $this->config->item('auth')['max_fail'])
		{
			die(json_encode(['code'=>0,'content'=>'超过最大登录错误次数限制{$adminInfo->login_fail}/$this->config->item(\'auth\')[\'max_fail\']}!']));
		}
		$this->loginModel->updateAdmin($adminInfo->id,['second'=>$adminInfo->second+=1,'ip'=>$this->input->ip_address()]);
		$this -> session -> set_userdata('admin', $adminInfo);
		die(json_encode(['code'=>1,'content'=>'登录成功，正在跳转...']));
	}
	public function hashPassword($password)
	{
		$hash = $this->config->item('auth')['passwordHashFunc'];
		if (!$hash)
		{
			$salt = $this->config->item('auth')['passwordSalt'];
			return md5(md5($password . $salt));
		}
		return $hash($password);
	}

	public function logout()
	{
		$this->session->unset_userdata('admin');
		return 1;
	}
	/**
	 * 密码强度
	 * @param $str
	 */
	public function judgePassword($str)
	{
		$score = 0;
		if (preg_match("/[0-9]+/", $str)) {
			$score++;
		}
		if (preg_match("/[0-9]{3,}/", $str)) {
			$score++;
		}
		if (preg_match("/[a-z]+/", $str)) {
			$score++;
		}
		if (preg_match("/[a-z]{3,}/", $str)) {
			$score++;
		}
		if (preg_match("/[A-Z]+/", $str)) {
			$score++;
		}
		if (preg_match("/[A-Z]{3,}/", $str)) {
			$score++;
		}
		if (preg_match("/[_|\-|+|=|*|!|@|#|$|%|^|&|(|)]+/", $str)) {
			$score += 2;
		}
		if (preg_match("/[_|\-|+|=|*|!|@|#|$|%|^|&|(|)]{3,}/", $str)) {
			$score++;
		}
		if (strlen($str) >= 10) {
			$score++;
		}
		return $score;
	}
}
